﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Daq.Services;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Daq.ViewModels.DeviceSettingsViewModels
{
    public partial class DataPreprocessViewModel : ObservableObject
    {
        [ObservableProperty]
        private DeviceService deviceService;
        private readonly SettingsService settings;
        private readonly IDialogService dialogService;
        public DataPreprocessViewModel(DeviceService deviceService, SettingsService settings, IDialogService dialogService)
        {
            DeviceService = deviceService;
            this.settings = settings;
            this.dialogService = dialogService;
        }

        [RelayCommand]
        private void GoToPreviousStep()
        {
            var vm = App.Current.Services.GetService<DeviceSettingsViewModel>();
            vm?.SelectStep("测量设置");
        }

        [RelayCommand]
        private void GoToNextStep()
        {
            var vm = App.Current.Services.GetService<DeviceSettingsViewModel>();
            vm?.SelectStep("预处理设置");
        }

        [ObservableProperty]
        [NotifyCanExecuteChangedFor(nameof(ClearTriggersCommand))]
        private DaqChannelInfo? selectedChannel;

        private bool CanClearTriggers => SelectedChannel != null;
        [RelayCommand(CanExecute=nameof(CanClearTriggers))]
        private void ClearTriggers()
        {
            if (SelectedChannel == null) return;
            SelectedChannel.Trigger.Logic = Logic.None;
            SelectedChannel.Trigger.Type1 = TriggerType.None;
            SelectedChannel.Trigger.Type2 = TriggerType.None;
            SelectedChannel.Trigger.Value1 = 0;
            SelectedChannel.Trigger.Value2 = 0;
        }

        [RelayCommand]
        private async Task Save()
        {
            await SaveChannelSettings();
        }

        [ObservableProperty]
        private bool isBusy;
        [ObservableProperty]
        private string? busyContent;
        private async Task<bool> SaveChannelSettings()
        {
            bool result = true;
            IsBusy = true;
            BusyContent = "保存通道参数";
            try
            {
                DeviceService.CheckChannelNames();
                await DeviceService.SaveSettings();
                await Task.Delay(500);
            }
            catch (Exception ex)
            {
                await dialogService.ShowMessageAsync("错误", $"通道参数保存失败:{ex.Message}");
                result = false;
            }
            IsBusy = false;
            BusyContent = null;
            return result;
        }
    }
}
